package com.mocha.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm{

    private Map<String, String> map = new HashMap<>();

    {
//        map.put("mocha", "123");
//        map.put("mocha", "202cb962ac59075b964b07152d234b70");
        map.put("mocha", "1e2a796539042ca860c3091662aa4346");
        setName("customRealm");
    }


    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //根据名称获角色数据
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        //获取权限
        Set<String> permissions = new HashSet<>();
        permissions.add("select");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String) authenticationToken.getPrincipal();

        String pwd = getPwdBuName(userName);
        if (pwd == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("mocha", pwd, "customRealm");
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("m"));//自定义Realm 加密加盐
        return authenticationInfo;
    }

    private String getPwdBuName(String userName) {
        return map.get(userName);
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123","m");
        System.out.println(md5Hash);
    }


}
